
/**
 * 数据表头的单元格
 * @param name           列标题
 * @param propertyName   列绑定的属性名称
 * @param cellWidth      列宽度
 * @param html           html 默认显示属性值
 * @param title 是否显示tips效果
 */
function TableHeadCell(name,propertyName,cellWidth,html,title)
{
	this.width = cellWidth;
	this.name  = name;
	this.propertyName = propertyName;
	this.html = html;
	this.title = title;
}
// 数据表的头
function TableHeadRow()
{
	this.displayCol = 0;
	this.cells = new Array();
	this.addColumn = function(name,propertyName,colWidth,html,title)
	{
		var col = new TableHeadCell(name,propertyName,colWidth,html,title);
		if(colWidth != 0)
		{
			this.displayCol += 1;
		}
		this.cells.push(col);
	};
	this.delAllColumn = function()
	{
		this.cells = null;
		this.cells = new Array();
	};
	
	this.getHtml = function()
	{
		var head = $("<thead/>");
		var tr = $("<tr/>");
		var th = $("<th/>");
		var cell;
		for(var i = 0; i < this.cells.length; i ++)
		{
			th = $("<th/>");
			cell = this.cells[i];
			if(cell.width != null && cell.width != '')
			{
				if(cell.width == 0)
				{
					th.css("display","none");
				}
				else
				{
					th.attr("width",cell.width);
				}
			}
			th.attr("title","");
			th.html(cell.name);
			tr.append(th);
		}
		head.append(tr);
		return head;
	};
}
// 数据表的行
function TableRow()
{
	var cells;
	this.setCells = function(cells)
	{
		this.cells = cells;
	};
	this.getHtml = function(rowData,rowNo)
	{
		var html = $("<tr/>");
	
		var colHtml;
		var cell;
		var txt = "";
		for(var i = 0; i < this.cells.length; i ++)
		{
			txt = "";
			cell = this.cells[i];
			// 如果单元中填充的html将所有属性值替换
			if(cell.html != null && cell.html != '')
			{
				if(cell.propertyName == "indexNo")
				{
					itemHtml = cell.html;
					var keys = cell.html.match(/\[.*?\]/g);
					for(k = 0; k < keys.length;k ++)
					{
						key = keys[k];
						key = key.replace("[","").replace("]","");
						if(key == "indexNo")
						{
							reg =  new RegExp("\\x5B"+ key +"\\x5D","g");
							itemHtml = itemHtml.replace(reg,rowNo);
						}
						else
						{
							reg =  new RegExp("\\x5B"+ key +"\\x5D","g");
							itemHtml = itemHtml.replace(reg,rowData[key]);
						}
						
					}
				}
				else
				{
					reg =  new RegExp("\\x5B"+ cell.propertyName +"\\x5D","g");
					itemHtml = cell.html.replace(reg,rowData[cell.propertyName]);
				}
				
			}
			else
			{
				if(cell.propertyName == "indexNo")
				{
					itemHtml = "" + rowNo;
				}
				else
				{
					//var value = $("<div/>").html(rowData[cell.propertyName]).text();
					var value = rowData[cell.propertyName];
					if(cell.title === true)
					{
						txt = value;
					}
					
					itemHtml = "" + value;
				}
			}
			/**
			 * 2016-01-15
			 * add  如果返回undefined或空，则返回""
			 */
			if(itemHtml==null)
			{
				itemHtml="";
			}
			
			if(cell.width != null && cell.width == 0)
			{
				colHtml = $("<td style='display: none;' />");
				colHtml.html(itemHtml);
			}
			else
			{
				colHtml = $("<td />");
				colHtml.html(itemHtml);
				colHtml.attr("title",txt);
			}
			
			html.append(colHtml);
		}
		return html;
	};
}
// 数据表对象

/**
 * 数据表类
 * @param entityName    类实体名称
 * @param containerId   显示数据表的容器ID
 * @param tableId       表的ID
 * @param hidePageCtrl  隐藏翻页控件
 */
function DataTable(entityName,containerId,tableId,hidePageCtrl)
{
	if(entityName == null || containerId == null)
	{
		alert("entityName和containerId不能为空！");
		return ;
	}
	this.entityName = entityName;
	this.containerId = containerId;
	this.tableId = tableId;
	this.hidePageCtrl = hidePageCtrl;
	this.tableHead = new TableHeadRow();
	var _self = this;
	
	
	
	this.getPageInfoHtml = function(pageData)
	{
		var _this = this;
		var pageInfo = $("<div class='zxui-page'/>");
		// 页大小
		var spageSizeSpan = $("<span class='zxui-pageSize' style='width:70px;margin-right:8px;'/>");
		spageSizeSpan.click(function(event)
		{
			//设置弹出层的位置  
			var offset = $(event.target).offset();  
	        //判断翻页按钮定位的位置
	        var bodyHeight = $(window).height();
			var topHeight = $(".location").height();
			var searchHeight = $(".searchForm").height();
			var tableHeight = $("#TableDiv").height();
			var pageHeight = bodyHeight-topHeight-searchHeight-tableHeight;
			if(pageHeight < 200){
				$(".zxui-pageSize #pageSize_div").removeClass("zxui-pageListBottom");
			 	$(".zxui-pageSize #pageSize_div").addClass("zxui-pageListTop");
			 }else{
				 $(".zxui-pageSize #pageSize_div").removeClass("zxui-pageListTop");
				 $(".zxui-pageSize #pageSize_div").addClass("zxui-pageListBottom");
			}
			//按钮的toggle,如果div是可见的,点击按钮切换为隐藏的;如果是隐藏的,切换为可见的。  
	        $(this).children("#pageSize_div").toggle();
	        event.stopPropagation();
		});
		
		var spageSizeInput = $("<input type='text' class='zxui-pageText' id='pageSize' readonly='readonly'/>");
		spageSizeInput.val(pageData.pageSize);
		var spageSizediv = $("<div class='zxui-pageListDiv' id='pageSize_div'/>");
		var spageSizedl = $("<dl class='zxui-pageList' id='pageSize_dl'/>");
		for(i = 1; i < 10; i ++)
		{
			var value = i * 5;
			var dd = $("<dd class='zxui-pageNum'/>");
			dd.val(value);
			dd.text(value);
			dd.mousedown(function()
			{
				_this.onPageSizeChanged($(this).text());
				$("#pageSize").val($(this).text());
			});
			spageSizedl.append(dd);
		}
		
		spageSizeSpan.append(spageSizeInput);
		spageSizeSpan.append(spageSizediv);
		spageSizediv.append(spageSizedl);
		pageInfo.append(spageSizeSpan);
		
		spageSizediv.click(function(event){
			spageSizediv.show();
			event.stopPropagation();	
		});
	 	$(document).click(function(){
	 		spageSizediv.hide();
		 });

		var firstPage = $("<a class='zxui-gohome' href='javascript:void(0);' title='首页'></a>");
		firstPage.click(_this.onFristPage);
		pageInfo.append(firstPage);
		if(parseInt(pageData.pageNum) > 1)
		{
			var perPage = $("<a class='zxui-gops' href='javascript:void(0);' onclick='table.onLastPage();' title='上一页'></a>");
			perPage.click(_this.onLastPage);
			pageInfo.append(perPage);
		}
		else
		{
			var perPage = $("<a class='zxui-gops' href='javascript:void(0);' title='上一页'></a>");
			pageInfo.append(perPage);
		}

		pageInfo.append($("<span> " + pageData.pageNum + "/ " + pageData.pageSum + "</span>"));
		
		if(parseInt(pageData.pageNum) < parseInt(pageData.pageSum))
		{
			var nextPage = $("<a class='zxui-gonext' href='javascript:void(0);' title='下一页'></a>");
			nextPage.click(_this.onNextPage);
			pageInfo.append(nextPage);
		}
		else
		{
			pageInfo.append($("<a class='zxui-gonext' href='javascript:void(0);' title='下一页'></a>"));
		}
		
		var lastPage = $("<a class='zxui-golast' title='尾页' href='javascript:void(0);'></a>");
		
		lastPage.click(_this.onTheLastPage);
		pageInfo.append(lastPage);
		pageInfo.append($("<span style='margin-left:10px;'>跳转至</span>"));
		pageInfo.append($("<input type='text' id='pageNum' class='page-num' value='" + pageData.pageNum + "' style='width:40px'/>"));
		var pageNumBtn = $("<input type='button' id='pageNumBtn' class='btn-num' value='跳转'/>");
		pageNumBtn.click(function()
			{
				_this.onPageNumChanged($(this).prev().val());
			});
		
		pageInfo.append(pageNumBtn);
		pageInfo.append($("<span> " +  "共 " + pageData.rowSum + " 条记录</span>"));
	    return pageInfo;
	};

	/**
	 * 添加索引列
	 * @param colWidth 列宽
	 * @param html     显示的内容，默认为列号
	 */
	this.addIndexColumn=function(colWidth,html,headHtml)
	{
		if(null == headHtml)
		{
			this.addColumn("序号","indexNo",colWidth,html);
		}
		else
		{
			this.addColumn(headHtml,"indexNo",colWidth,html);
		}
		
	};
	/**
	 * 增加表列
	 * @param name 列标题
	 * @param propertyName 列绑定的类属性名
	 * @param colWidth 列宽
	 * @param html 列的内容，默认为属性值
	 * @param title 是否显示tips效果
	 */
	this.addColumn = function(name,propertyName,colWidth,html,title)
	{
		var titleTemp;
		if(title == undefined || title == null)
		{
			titleTemp = true;
		}
		else
		{
			titleTemp = title;
		}
		this.tableHead.addColumn(name, propertyName, colWidth,html,titleTemp);
	};
	/**
	 * 填充数据表的空行
	 * @param rowCount 要填充的行数
	 */
	this.fullTable = function(rowCount)
	{
		if(this.tableHead == null || this.tableHead.cells == null || this.tableHead.cells.length <= 0)
		{
			return;
		}
		var tableHtml = $("<table border='0' cellspacing='0' cellpadding='0' class='table-bordered'/>");
		if(tableId != null)
		{
			tableHtml.attr("id",tableId);
		}
				
		tableHtml.append(this.tableHead.getHtml());
		
		
		var row = $("<tr/>");
		// 判断第一列是否为序号
		if(this.tableHead.cells[0].propertyName == "indexNo")
		{
			for(var col = 0; col < this.tableHead.cells.length; col ++)
			{
				var td = $("<td> </td>");
				row.append(td);
				
			}
			// 填充空行
			for(var i = 0; i < rowCount; i ++)
			{
				var rowNew = row.clone();
				rowNew.children(":first").text(i + 1);
				tableHtml.append(rowNew);
			}
		}
		else
		{
			for(var col = 0; col < this.tableHead.cells.length; col ++)
			{
				row.append($("<td> </td>"));
			}
			// 填充空行
			for(var i = 0; i < rowCount; i ++)
			{
				tableHtml.append(row.clone());
			}
		}
		
		var pageInfo = new Object();
		pageInfo.pageSize = 15;
		pageInfo.pageNum = 0;
		pageInfo.pageSum = 0;
		pageInfo.rowSum  = 0;
		
		var tfootTd = $("<td align='right' colspan = '" + this.tableHead.displayCol + "'/>");
		tfootTd.append(this.getPageInfoHtml(pageInfo));
		var tfootTr = $("<tr/>");
		tfootTr.append(tfootTd);
		this.tableFoot = $("<tfoot/>");
		this.tableFoot.append(tfootTr);
		//tableHtml.append(tfoot);
		
		$("#"+this.containerId).html(tableHtml);
	};
	
	/**
	 * 填充数据表
	 * @param dataPage 后台返回的数据对象
	 */
	this.fullData = function(dataPage)
	{
		
		this.tableRows = new Array();
		this.pageInfo = new Object();
		this.pageInfo.pageSize = dataPage.pageSize;
		this.pageInfo.pageNum = dataPage.pageNum;
		this.pageInfo.pageSum = dataPage.pageSum;
		this.pageInfo.rowSum = dataPage.rowSum;
		this.pageInfo.hql      = dataPage.hql;
		this.pageInfo.queryParameter =dataPage.queryParameter;
		var data = dataPage.dataList;
		var dataItem;
		var tableRow = new TableRow();
		tableRow.setCells(this.tableHead.cells);
		if(data == null || data.length < 1)
		{
			this.tableRows.push($("<tr><td class='tips' colspan='"+ this.tableHead.cells.length +"' align='center' >没有查到，请确认您当前的查询条件是否正确。</td></tr>"));
			this.tableFoot = null;
		}
		else
		{
			for(var i = 0; i < data.length; i ++)
			{
				dataItem = data[i];
				this.tableRows.push(tableRow.getHtml(dataItem,i + 1 + this.pageInfo.pageSize * (this.pageInfo.pageNum-1)));
			}
			var tfootTd = $("<td align='right' colspan = '" + this.tableHead.displayCol + "'/>");
			tfootTd.append(this.getPageInfoHtml(dataPage));
			var tfootTr = $("<tr/>");
			tfootTr.append(tfootTd);
			this.tableFoot = $("<tfoot/>");
			this.tableFoot.append(tfootTr);
		}
		
		$("#"+this.containerId).html(this.getHtml());
		// 设置表格行点击函数
		var _this = this;
		$("#" + this.tableId + " tbody tr").click(
			function(e)
			{
				$(e.delegateTarget.cells).addClass("odd1");
				$(e.delegateTarget.cells).siblings().removeClass("odd1");
				if(_this.onRowClick != null)
				{
					// 调用行点击回调函数
					_this.onRowClick(e.delegateTarget.cells);
				}
			}
		);
		//IE8模式下表格隔行变色
		$("#" + this.tableId + " tbody tr:odd").addClass("odd");
	};

	/**
	 * 设置点击行的回调函数
	 * onRowClick回调函数
	 * onRowClick(cells) cells是td的数组
	 */
	this.setOnRowClick=function(onRowClick)
	{
		this.onRowClick = onRowClick;
	};
	/**
	 * 获取数据表的html
	 */
	this.getHtml = function()
	{
		
		var tableHtml = $("<table border='0' cellspacing='0' cellpadding='0' class='table-bordered'/>");
		
		if( tableId != null)
		{
			tableHtml.attr("id",tableId);
		}
		
		// 表头
		tableHtml.append( this.tableHead.getHtml());
		
		// 表行
		var tbody = $("<tbody/>");
		for(var i = 0; i < this.tableRows.length; i ++)
		{
			
			dataRow = this.tableRows[i];
			tbody.append(dataRow);
		}
		tableHtml.append(tbody);
		// 表尾
		// 填充分页
		if(this.hidePageCtrl == null || !this.hidePageCtrl)
		{
			if( this.tableFoot != null)
			{
				tableHtml.append(this.tableFoot); 
			}
		}
		return tableHtml;
	};
	
	/**
	 * 处理数据表的pagesize改变
	 * @param select pageSize的select对象
	 */
	this.onPageSizeChanged = function(pageSize)
	{
		// 保证切换了页大小，跳转到第一页
		_self.pageInfo.pageNum = 0;
		// end
		_self.pageQuery(pageSize, _self.pageInfo.pageNum);
	};
	/**
	 * 处理数据表的页数改变
	 * @param select pageNum的select对象
	 */
	this.onPageNumChanged =function (pageNum)
	{
		_self.pageQuery(_self.pageInfo.pageSize, pageNum);
	};

	/**
	 * 处理分页查询
	 * @param pageSize 页大小
	 * @param pageNum 显示的页号
	 */
	this.pageQuery = function(pageSize,pageNum)
	{
		var waitLayer  =  new LayerDialog();
		var _this = this;
		var entity = new Object();
		entity = this.pageInfo.queryParameter.params;
		entity["hql"] = this.pageInfo.hql;
		entity["pageSize"] = pageSize;
		entity["pageNum"] = pageNum;
		var isComplete = false;
		$.ajax({
			url:_this.pageUrl,
			async:false,
			type:'post',
			dataType:'json',
			data:entity,
			success:function(data)
			{
				_this.fullData(data,table.containerId);
				if(_this.OnFulled != null)
				{
					_this.OnFulled(_this);
				}
			},
			beforeSend:function()
			{
				setTimeout(function()
						{
							if(!isComplete)
							{
								waitLayer.showWaitLayer("请稍后",240, 160);
							}
							
						},500);
				
			},
			complete:function()
			{
				isComplete = true;
				waitLayer.closeDialog();
			}
		});	
	};
	
	/**
	 * 显示首页
	 */
	this.onFristPage = function()
	{
		_self.pageQuery(_self.pageInfo.pageSize, 1);
	};
	/**
	 * 显示下一页
	 */
	this.onNextPage = function()
	{
		var pageNum = parseInt(_self.pageInfo.pageNum);
		if(pageNum < parseInt(_self.pageInfo.pageSum))
		{
			pageNum += 1;
			_self.pageQuery(_self.pageInfo.pageSize, pageNum);
		}
		else
		{
			alert("已经是最后一页了！");
		}
	};
	/**
	 * 显示上一页
	 */
	this.onLastPage =function()
	{
		var pageNum = parseInt(_self.pageInfo.pageNum);
		if(pageNum >= 1)
		{
			pageNum -= 1;
			_self.pageQuery(_self.pageInfo.pageSize, pageNum);
		}
		else
		{
			alert("已经是第一页了！");
		}
	};
	
	/**
	 * 显示最后一页
	 */
	this.onTheLastPage =function()
	{
		_self.pageQuery(_self.pageInfo.pageSize, _self.pageInfo.pageSum);
	};
	
	
	this.queryDataByParameter=function(queryParameter,urlAction)
	{
		
		var waitLayer  =  new LayerDialog();
		if(urlAction == null)
		{
			this.pageUrl = "../" + this.entityName + "Action_queryList.action";
		}
		else
		{
			this.pageUrl = urlAction;
		}
		
    	var queryItem = queryParameter;
    	
    	// 查询时保存原来的页大小pageSize参数
    	if(this.pageInfo != null && this.pageInfo.pageSize != null)
    	{
    		queryItem["pageSize"] = this.pageInfo.pageSize;
    	}
    	var _this = this;
    	var isComplete = false;
    	$.ajax({
				url:this.pageUrl,
				async:false,
				type:'post',
				dataType:'json',
				data:queryItem,
				success:function(data)
				{
					_this.fullData(data);
					if(_this.OnFulled != null)
					{
						_this.OnFulled(_this);
					}
				},
				error:function(event,xhr,options,exc)
				{
					alert("Error");
				},
				beforeSend:function()
				{
					setTimeout(function()
							{
								if(!isComplete)
								{
									waitLayer.showWaitLayer("请稍后",240, 160);
								}
								
							},500);
				},
				complete:function()
				{
					isComplete = true;
					waitLayer.closeDialog();
				}
			});	
	};
	/**
	 * 查询数据
	 * @param queryDivID 查询条件的容器ID
	 * @param urlAction 查询处理的后台url 默认为实体Action的queryList函数
	 */
	this.queryData=function(queryDivId,urlAction)
	{
		if(queryDivId == null)
		{
			alert("queryDivId 不能为空!");
			return ;
		}
		var waitLayer  =  new LayerDialog();
		if(urlAction == null)
		{
			this.pageUrl = "../" + this.entityName + "Action_queryList.action";
		}
		else
		{
			this.pageUrl = urlAction;
		}
		var childs = $("#" + queryDivId + " span").children();
    	var queryItem = new Object;
    	for(i = 0; i < childs.length;i ++)
    	{
    		var obj = $(childs[i]);
    		if(obj.attr("id") != null)
    		{
    			queryItem[obj.attr("id")] = obj.val();
    		}
    	}
    	// 查询时保存原来的页大小pageSize参数
    	if(this.pageInfo != null && this.pageInfo.pageSize != null)
    	{
    		queryItem["pageSize"] = this.pageInfo.pageSize;
    	}
    	var _this = this;
    	var isComplete = false;
    	$.ajax({
				url:this.pageUrl,
				async:false,
				type:'post',
				dataType:'json',
				data:queryItem,
				success:function(data)
				{
					_this.fullData(data);
					if(_this.OnFulled != null)
					{
						_this.OnFulled(_this);
					}
				},
				error:function(event,xhr,options,exc)
				{
					alert("Error");
				},
				beforeSend:function()
				{
					setTimeout(function()
							{
								if(!isComplete)
								{
									waitLayer.showWaitLayer("请稍后",240, 160);
								}
								
							},500);
				},
				complete:function()
				{
					isComplete = true;
					waitLayer.closeDialog();
				}
			});	
	};
	
	// 增加遍历行的回调函数
	this.RowCallback=function(rowCallback)
	{
		$("#" + this.tableId + " tbody tr").each(rowCallback);
	};
	
	/**
	 * 数据填充完成后的回调函数
	 */
	this.setOnFulled=function(onFulled)
	{
		this.OnFulled = onFulled;
	};
	
}